package cn.lili.controller.feign.citydistribution;

import cn.hutool.core.collection.CollectionUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.member.client.CityDistributionClient;
import cn.lili.modules.member.entity.dos.CityDistribution;
import cn.lili.modules.member.entity.dos.CityDistributionCancel;
import cn.lili.modules.member.entity.dto.CityDistributionDTO;
import cn.lili.modules.member.service.CityDistributionCancelService;
import cn.lili.modules.member.service.CityDistributionService;
import cn.lili.modules.system.client.IRegionClient;
import cn.lili.modules.system.entity.dos.Region;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@Slf4j
public class CitydistributionFeignController implements CityDistributionClient {

    private final CityDistributionService cityDistributionService;

    private final IRegionClient regionClient;

    private final CityDistributionCancelService cityDistributionCancelService;

    /**
     * 通过id查找城主信息
     *
     * @param id
     * @return
     */
    @Override
    public CityDistribution getCityDistributionById(String id) {
        return cityDistributionService.getById(id);
    }


    @Override
    public Page<CityDistribution> getCityDistribution(CityDistributionDTO dto) {
        return cityDistributionService.getCityDistribution(dto);
    }

    /**
     * 创建城主
     *
     * @param cityDistribution 城主对象
     * @return 是否成功
     */
    @Override
    public Boolean createCityDistribution(CityDistribution cityDistribution) {
        return cityDistributionService.saveOrUpdate(cityDistribution);
    }


    /**
     * 更新城主信息
     *
     * @param city
     * @return
     */
    @Override
    public Boolean updateCityDistributionById(CityDistribution city) {
        return cityDistributionService.updateById(city);
    }


    /**
     * 初始化城主信息
     * 1.判断是否已经初始化本月数据
     * 2.已经初始化就不执行了。
     * 3.没有初始化，去构建集合。去批量执行保存
     */
    @Override
    public void initCityDistribution() {
        // 判断是否已经初始化本月数据
        YearMonth yearMonth = YearMonth.now();
        LambdaQueryWrapper<CityDistribution> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CityDistribution::getYearDate, yearMonth.getYear());
        queryWrapper.eq(CityDistribution::getMonthDate, yearMonth.getMonthValue());
        long count = cityDistributionService.count(queryWrapper);
        log.info("initCityDistribution count == {}", count);
        // 已经初始化就不执行了。
        if (count > 0) {
            return;
        }
        // 根据区域生成，每个区域的数据
        List<Region> regionList = regionClient.getRegionList();
        log.info("regionList == {}", JSONObject.toJSONString(regionList));
        if (CollectionUtil.isEmpty(regionList)) {
            return;
        }
        List<CityDistribution> cityDistributionList = new ArrayList<>();
        //需要初始化的区域
        List<Region> newForRegion = regionList.stream().filter(f -> "district".equals(f.getLevel())).toList();
        if (CollectionUtil.isEmpty(newForRegion)) {
            return;
        }
        for (Region region : newForRegion) {
            CityDistribution cityDistribution = new CityDistribution();
            cityDistribution.setDistrictCode(region.getId());
            cityDistribution.setDistrictName(region.getName());
            //获取市级数据
            Region cityRegion = this.getParentRegion(regionList, region.getParentId());
            if (cityRegion != null) {
                cityDistribution.setCityCode(cityRegion.getId());
                cityDistribution.setCityName(cityRegion.getName());
                //获取省级数据
                Region privinceRegion = this.getParentRegion(regionList, cityRegion.getParentId());
                if (privinceRegion != null) {
                    cityDistribution.setPrivinceCode(privinceRegion.getId());
                    cityDistribution.setPrivinceName(privinceRegion.getName());
                }
            }
            cityDistribution.setComissStatus(1);
            cityDistribution.setYearDate(yearMonth.getYear());
            cityDistribution.setMonthDate(yearMonth.getMonthValue());
            cityDistribution.setDistributionStatus(true);
            cityDistributionList.add(cityDistribution);
        }
        // 批量执行保存
        if (CollectionUtil.isNotEmpty(cityDistributionList)) {
            cityDistributionService.saveBatch(cityDistributionList);
        }
    }

    /**
     * 获取父级数据
     * @return 父级数据
     */
    private Region getParentRegion(List<Region> regionList, String parentId) {
        Region result = null;
        if (StringUtils.equals(parentId,"0")) {
            return null;
        }
        for (Region region : regionList) {
            if (region.getId().equals(parentId)) {
                result = region;
                break;
            }
        }
        return result;
    }

    @Override
    public CityDistribution getCityDistributionByDistrictCodeAndMonthDate(String regionId) {
        LambdaQueryWrapper<CityDistribution> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CityDistribution::getDistrictCode, regionId);
        queryWrapper.eq(CityDistribution::getMonthDate, YearMonth.now().getMonthValue());
        queryWrapper.eq(CityDistribution::getYearDate, YearMonth.now().getYear());
        queryWrapper.last("limit 1");
        return cityDistributionService.getOne(queryWrapper);
    }

    @Override
    public List<CityDistributionCancel> getCityDistributionCancelByRegion(String regionId) {
        LambdaQueryWrapper<CityDistributionCancel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CityDistributionCancel::getYearDate, YearMonth.now().getYear());
        queryWrapper.eq(CityDistributionCancel::getMonthDate, YearMonth.now().getMonthValue());
        queryWrapper.eq(CityDistributionCancel::getDistrictCode, regionId);
        return cityDistributionCancelService.list(queryWrapper);
    }
}
